package com.xulu.romance.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.xulu.romance.service.SendMailService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;
/**
 * @author xiaoxulu
 * @version V1.0
 * @Package com.xulu.romance.service.impl
 * @date 2024/2/6 16:46
 */
@Service
public class SendMailServiceImpl implements SendMailService {
    @Resource
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${spring.mail.username}")
    private String from;


    @Override
    public boolean sendMailService(String mail) {
        String code = RandomUtil.randomNumbers(6);
        String context="[Romance]您的验证码为"+code+",有效期为2分钟,请勿透露给他人。";
        stringRedisTemplate.opsForValue().set(mail,code,120, TimeUnit.SECONDS);

        MimeMessage message=mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(mail);
            mimeMessageHelper.setSubject("Romance");
            mimeMessageHelper.setText(context,true);
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }
}
